import React, { Component, createRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons';
import Captcha from '../../component/Captcha';
// 导入资源组件
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from "react-router-dom"

class Password extends Component {
  constructor(props) {
    super(props)
    this.capRef = createRef()
  }
  state = {}
  render() {
    return (
      <div>
        <div>
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{}}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: '请填写用户名',
                },
              ]}
            >
              <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请填写密码',
                },
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请填写验证码',
                },
              ]}
            >
              <div>
                <Input
                  prefix={<KeyOutlined className="site-form-item-icon" />}
                  type="text"
                  placeholder="验证码"
                  style={{ width: "70%", marginRight: "5px" }}
                />
                <Captcha w={96} h={32} setKey={this.getKey} ref={this.capRef}></Captcha>
              </div>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }

  getKey = (key) =>  {
    this.setState({
      key
    })
  }

  onFinish = (values) => {
    // 将key值补录到values中
    values.key = this.state.key
    // 发送请求
    req.post(url.PasswordLogin, values).then((res) => {
      if (res.data.errNo === 0) {
        message.success("登录成功", 2, () => {
          this.props.history.push("/dashboard")
        })
      } else {
        message.error(res.data.errText, 2, () => {
          // 刷新验证码
          this.capRef.current.loadCaptcha()
        })
      }
    })
  }
}

export default withRouter(Password);
